package com.yazi.mxz.common.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.myframework.smhj.common.exception.MyEntityNotExistsException;
import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyIllegalArgumentException;
import com.myframework.smhj.common.exception.MyNoPermissionException;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yazi.mxz.common.MyUtil;
import com.yazi.mxz.common.db.dao.ShoppingCartDao;
import com.yazi.mxz.common.db.dao.ShoppingDao;
import com.yazi.mxz.common.db.dao.StoreGoodsDao;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.Shopping;
import com.yazi.mxz.common.entity.beans.ShoppingCart;
import com.yazi.mxz.common.entity.beans.StoreGoods;
import com.yazi.mxz.common.exception.Code;
import com.yazi.mxz.common.exception.MxzStoreGoodsException;
import com.yazi.mxz.common.service.ShoppingService;

@Service("shoppingService")
public class ShoppingImpl extends BasicService<Shopping> implements ShoppingService {
	private static Logger log = LoggerFactory.getLogger(ShoppingImpl.class);

	@Resource
	ShoppingDao shoppingDao;
	@Resource
	ShoppingCartDao shoppingCartDao;
	@Resource
	StoreGoodsDao storeGoodsDao;

	@Override
	protected Dao<Shopping> getDao() {
		return shoppingDao;
	}
	
	@Override
	public Shopping addByMember(Member member, Shopping shopping) throws MyException {

		Long storeGoodsId = null;

		if (null == shopping.getStoreGoods()
				|| null == (storeGoodsId = shopping.getStoreGoods().getStoreGoodsId())
				|| null == shopping.getBuyCount() || 0 == shopping.getBuyCount()) {
			throw new MyIllegalArgumentException();
		}

		log.debug("addByMember：memberId={},storeGoodsId={}", member.getMemberId(), storeGoodsId);

		StoreGoods storeGoods = storeGoodsDao.get(storeGoodsId);

		if (null == storeGoods) {
			throw new MyEntityNotExistsException();
		}

		// 购物车
		ShoppingCart shoppingCart = null;

		// 查询购物车
		ShoppingCart cart4s = new ShoppingCart();// cartForSearch
		cart4s.setMember(member);
		cart4s.setStore(storeGoods.getStore());
		List<ShoppingCart> shoppingCartList = shoppingCartDao.listByExample(cart4s);

		// 购物车中的物品
		List<Shopping> list = new ArrayList<Shopping>();

		if (shoppingCartList.size() == 0) {// 创建购物车

			shoppingCart = new ShoppingCart();
			shoppingCart.setMember(member);
			shoppingCart.setStore(storeGoods.getStore());
			shoppingCartDao.persist(shoppingCart);

		} else {// 现有购物车
			shoppingCart = shoppingCartList.get(0);

			// 查询购物车中的物品
			Shopping shopping4s = new Shopping();// shoppingForSearch
			shopping4s.setMemberId(member.getMemberId());
			shopping4s.setStoreGoods(storeGoods);
			shopping4s.setShoppingCart(shoppingCart);
			list = shoppingDao.listByExample(shopping4s, new Searching()).getList();
		}

		if (list.size() == 0) {// 购物车中没有该物品

			// 库存不足
			if (storeGoods.getStockConvert() < shopping.getBuyCount()) {
				throw new MxzStoreGoodsException(Code.ERR_10002, storeGoods);
			}

			log.debug("addByMember->add: storeGoodsId={},count={}", new Object[] { storeGoodsId,
					shopping.getBuyCount() });

			shopping.setShoppingCart(shoppingCart);
			shopping.setMemberId(member.getMemberId());
			return shoppingDao.persist(shopping);

		} else {// 购物车中已有该物品

			Shopping oldShopping = list.get(0);

			float destCount = oldShopping.getBuyCount() + shopping.getBuyCount();

			// 库存不足
			if (storeGoods.getStockConvert() < destCount) {
				throw new MxzStoreGoodsException(Code.ERR_10002, storeGoods);
			}

			log.debug(
					"addByMember->modify: shoppingId={},oldCount={},extCount={}",
					new Object[] { oldShopping.getShoppingId(), oldShopping.getBuyCount(),
							shopping.getBuyCount() });

			oldShopping.setBuyCount(destCount);
			return shoppingDao.persist(oldShopping);
		}

	}

	@Override
	public void editBuyCountByMemberId(long memberId, long shoppingId, float buyCount)
			throws MyException {

		log.debug("editBuyCountByMemberId：memberId={},shoppingId={},buyCount={}", new Object[] {
				memberId, shoppingId, buyCount });

		if (buyCount < 0) {
			throw new MyIllegalArgumentException("购买量必须大于0");
		}

		Shopping oldShopping = shoppingDao.get(shoppingId);
		if (null == oldShopping) {
			throw new MyEntityNotExistsException();
		}
		if (memberId != oldShopping.getMemberId()) {
			throw new MyNoPermissionException();
		}

		StoreGoods storeGoods = oldShopping.getStoreGoods();
		// 库存不足
		if (storeGoods.getStockConvert() < buyCount) {
			throw new MxzStoreGoodsException(Code.ERR_10002, storeGoods);
		}

		oldShopping.setBuyCount(MyUtil.numRoundDown(buyCount, 1).floatValue());
		shoppingDao.persist(oldShopping);
	}

	@Override
	public void removeByMemberId(long memberId, Long[] shoppingIds) {
		log.debug("removeByMemberId：memberId={},shoppingIds={}", memberId, shoppingIds);
		// 删除购物车物品
		shoppingDao.deleteByIds(memberId, shoppingIds);
		// 删除用户空的购物车
		shoppingCartDao.deleteEmptyByMemberId(memberId);
	}

	@Override
	public Integer countOfMemberId(long memberId) {
		log.debug("countOfMemberId：memberId={}", memberId);
		Shopping shopping = new Shopping();
		shopping.setMemberId(memberId);
		return shoppingDao.countByExample(shopping);
	}

	@Override
	public Float countOfStoreGoodsId(long memberId, long storeGoodsId) {
		log.debug("countOfStoreGoodsId：memberId={},storeGoodsId={}", memberId, storeGoodsId);

		StoreGoods storeGoods = new StoreGoods();
		storeGoods.setStoreGoodsId(storeGoodsId);

		Shopping shopping = new Shopping();
		shopping.setMemberId(memberId);
		shopping.setStoreGoods(storeGoods);
		List<Shopping> list = shoppingDao.listByExample(shopping);

		return list.size() == 0 ? 0 : list.get(0).getBuyCount();
	}

}
